from django.shortcuts import render
from django import http
from alipay import AliPay
from django.conf import settings
import os

from meiduo_mall.utils.views import LoginRequiredView
from orders.models import OrderInfo
from meiduo_mall.utils.response_code import RETCODE
from .models import Payment


class PaymentURLView(LoginRequiredView):
    """拼接支付宝登录url"""
    def get(self, request, order_id):

        # 校验
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden('订单有误')

        # 创建alipay 工具对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,  # 应用id
            app_notify_url=None,  # 默认回调url
            # /Users/chao/Desktop/meiduo_34/meiduo_mall/meiduo_mall/apps/payment/keys/app_private_key.pem
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),  # 应用私钥文件绝对路径
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/alipay_public_key.pem'),  # 支付宝公钥文件绝对路径
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 沙箱应用还是真实应用
        )
        # 调用api_alipay_trade_page_pay方法得到支付宝登录url 后面查询参数部分
        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # order_id
            total_amount=str(order.total_amount),  # 支付金额, 不支付Decimal类型需要转字符串
            subject='美多商城:%s' % order_id,  # 主题
            return_url=settings.ALIPAY_RETURN_URL,  # 支付成功后重定向回url
        )
        # https://openapi.alipay.com/gateway.do? + order_string  # 真实支付url
        # https://openapi.alipaydev.com/gateway.do? + order_string  # 沙箱支付url 中间多一个dev
        # 拼接支付宝登录url
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})


class PaymentStatusView(LoginRequiredView):
    """校验及保存支付结果"""
    def get(self, request):

        # 接收
        query_dict = request.GET
        # 将Query_dict 类型对象转换成dict
        data = query_dict.dict()
        # 将sign 加密数据单独移除 pop
        sign = data.pop('sign')

        # 创建alipay工具对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,  # 应用id
            app_notify_url=None,  # 默认回调url
            # /Users/chao/Desktop/meiduo_34/meiduo_mall/meiduo_mall/apps/payment/keys/app_private_key.pem
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            # 应用私钥文件绝对路径
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_public_key.pem'),  # 支付宝公钥文件绝对路径
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 沙箱应用还是真实应用
        )
        # 调用sdk中 verify方法进行校验支付结果
        if alipay.verify(data, sign):
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')
            # 保存支付结果
            try:
                # 如果try里面查到了,说明此支付结果已保存订单状态也已经修改,
                Payment.objects.get(trade_id=trade_id, order_id=order_id)
            except Payment.DoesNotExist:
                Payment.objects.create(
                    order_id=order_id,
                    trade_id=trade_id
                )
                # 修改订单状态
                OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'], user=request.user).update(
                    status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']
                )
            # 响应
            return render(request, 'pay_success.html', {'trade_id': trade_id})

        else:
            # 校验失败
            return http.HttpResponseServerError('订单支付失败')



# http://www.meiduo.site:8000/payment/status/?
# charset=utf-8&out_trade_no=20200330092203000000001&method=alipay.trade.page.pay.return&total_amount=3798.00&
# &trade_no=2020033022001443550500635897&auth_app_id=2016091900551154&version=1.0&app_id=2016091900551154&sign_type=RSA2&seller_id=2088102176399893&timestamp=2020-03-30+09%3A54%3A46


#sign=CmlyJ0loJIs5OttG4XH%2Byq2R8RR%2BwTNXVOpgao9cjkckr79%2FimM9Iw6JjPXfVYlxPVslMaWndHyi4jdnsZL7UhG21e87%2F6Iyj2Eqye8pHTyCCumNbjsOUMKgfC0VEp7dDJ1BNzF9Pu2lGjmmDc%2FRxFVaYI10%2F1fg11uG92whFkkqZYjmv%2BAtyA4mxzTtNYhwhxE4oFV%2F5LVj77OW5D%2BVAm5tKCNzIW8j%2B%2FdwPh5OLi2xU5HPWipV3DLWlvOoPFZWy9Vz%2Byv0ru4KKAeS1skG9bUzYqg8Ys9K0R51I8XMR6Oq3EQOv%2FLrm7mgVK2Smf%2BGb%2F48WiEWqFYy%2FMcqckv9PA%3D%3D